<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // window.getUserInfo = function (data) {
    //   console.log(data);
    // }
    // const jsonp = function ({ url, params, callbackName }) { // 传入一个对象 有url,params和回调函数名字
    //   return new Promise((resolve, reject) => {
    //     const scriptSrc = generateUrl()
    //     const scriptEle = document.createElement('script')
    //     scriptEle.src = scriptSrc
    //     document.body.appendChild(scriptEle)
    //     resolve()
    //   })
    //   function generateUrl () {
    //     let dataSrc = [] // 解析params对象 生成= & ? 的字符串拼接上callbackName函数名 后端需要返回这个的callbackName(result) result是json数据格式的
    //     for (let key in params) {
    //       dataSrc.push(`${key}=${params[key]}`)
    //     }
    //     dataSrc = url + "?" + dataSrc.join('&') + `&callbackName=${callbackName}`
    //     return dataSrc
    //   }
    // }
    function getUserInfo (data) {
      console.log(data);
    }
    function jsonp ({
      url,
      params,
      callbackName
    }) {
      let srcUrl = getUrl(url, params, callbackName)
      let script = document.createElement('script')
      script.src = srcUrl
      document.body.appendChild(script)
    }
    function getUrl (url, params, callbackName) {
      let dataSrc = []
      for (let key of Object.keys(params)) {
        dataSrc.push(key + '=' + params[key])
      }
      url += ('?' + dataSrc.join('&'))
      url += '&callbackName=' + callbackName
      return url
    }
    jsonp({
      url: 'http://localhost:3000/api/jsonp',
      params: { name: '方现伟', password: 123456 },
      callbackName: 'getUserInfo'
    })
  </script>
</body>

</html>